package demo18_CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author kunkun
 * @className Test03_ABS_Solution
 * @Description 解决ABS问题
 * @date 2025/3/8 18:44
 */
public class Test03_ABS_Solution {

    public static void main(String[] args) {

        //使用带版本号的原子操作数据：AtomicStampedReference
        AtomicStampedReference reference = new AtomicStampedReference<Integer>(1,1);

        //模拟线程A，主线程
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"当前的stamp："+reference.getStamp());
            System.out.println(Thread.currentThread().getName()+"执行结果-1："+reference.compareAndSet(1, 3,
                    1, 2));
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+"当前的stamp："+reference.getStamp());
            System.out.println(Thread.currentThread().getName()+"执行结果-2："+reference.compareAndSet(3, 5,
                    2, 3));

        },"A").start();

        //模拟线程B
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+"当前的stamp："+reference.getStamp());
            System.out.println(Thread.currentThread().getName()+"执行结果-1："+reference.compareAndSet(1, 2,
                    1, 2));
            System.out.println(Thread.currentThread().getName()+"执行结果-2："+reference.compareAndSet(2, 1,
                    2, 3));
        },"B").start();

    }

}
